﻿using GeneralServices.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneralServices.Model
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class UnitOfWork<T> : IUnitOfWork<T> where T : class
    {
        private DbContext _db;

        #region Propriété
        /// <summary>
        /// 
        /// </summary>
        public DbContext Db
        {
            get { return _db; }
        }
        #endregion

        #region Constructeur
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public UnitOfWork(DbContext context)
        {
            _db = context;
        }
        #endregion
        
        #region IDisposable Membres

        void IDisposable.Dispose()
        {
            _db.Database.Connection.Close();
            _db = null;
        }

        #endregion

        #region IUnitOfWork Membres

        public int Commit()
        {
            UnitOfWorkGeneral.SaveT<T>(_db);
            int a =  _db.SaveChanges();
            return a;
        }

        public void RollBackAll()
        {
            UnitOfWorkGeneral.RollBackTotal<T>(_db);
            _db.Set<T>().Load();
        }

        public void RollBack(T entity)
        {
            _db.Entry<T>(entity).State = EntityState.Detached;
            _db.Entry<T>(entity).Reload();
        }

        #endregion
                 
    }
}
